package io.gitee.kotle.demo.mvvm_demo.pic

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.activity.result.ActivityResult
import androidx.appcompat.app.AppCompatActivity
import androidx.core.os.bundleOf
import androidx.recyclerview.widget.GridLayoutManager
import io.gitee.kotle.android.adapter.recyclerViewAdapter
import io.gitee.kotle.android.adapter.refreshList
import io.gitee.kotle.android.delegate.bundleDelegate
import io.gitee.kotle.android.delegate.viewModelDelegate
import io.gitee.kotle.android.mvvm.binding.FragmentContainerActivity
import io.gitee.kotle.android.mvvm.mvvminterface.MvvmViewType
import io.gitee.kotle.android.utils.*
import io.gitee.kotle.android.widget.BaseRecyclerView
import io.gitee.kotle.base.library.BaseFragment
import io.gitee.kotle.base.observerStatusDataAttachView

class PicFragment : BaseFragment() {
    companion object {
        fun start(
            appCompatActivity: AppCompatActivity,
            helper: ActivityResultHelper<Intent, ActivityResult>
        ) {

            FragmentContainerActivity.invoke<PicFragment>(appCompatActivity) {
                helper.launch(it) {
                    it.data?.getStringExtra("test").toast()
                }
            }
        }

        fun startBlur(context: Context, datas: List<PicBean.ImagesDTO>) {
            context.startFragment<PicFragment>(
                arguments = bundleOf(
                    "datas" to datas
                )
            )
        }


    }

    private val datas by bundleDelegate("datas", listOf<PicBean.ImagesDTO>())

    private val picAdapter = recyclerViewAdapter<Any>(::onPicSame, ::onPicSame)
    private fun onPicSame(old: Any?, new: Any?): Boolean {
        return if (old is PicBean.ImagesDTO && new is PicBean.ImagesDTO) {
            old.url == new.url
        } else {
            false
        }
    }

    override fun onMvvmCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): MvvmViewType? {
        appCompatActivity.setResult(100, Intent().apply {
            putExtra("test", "从图片页面返回")
        })
        picAdapter.register(PicHolder::class.java)
        picAdapter.register(LoadMoreHolder::class.java)
        return MvvmViewType.ViewInstanceType(BaseRecyclerView(inflater.context).apply {
            adapter = picAdapter
            layoutManager = GridLayoutManager(inflater.context, 2).apply {
                spanSizeLookup = object : GridLayoutManager.SpanSizeLookup() {
                    override fun getSpanSize(position: Int): Int {
                        return if (picAdapter.getItem(position) !is PicBean.ImagesDTO) {
                            2
                        } else {
                            1
                        }
                    }
                }
            }
        })
    }

    private val viewModel by viewModelDelegate<PicViewModel>()
    override fun initUi(savedInstanceState: Bundle?) {
        super.initUi(savedInstanceState)
        viewModel.picData.observerStatus(::onPicData)
    }


    private fun onPicData(observer: StatusDataObserver<PageHelper<Any, Any>>) {
        observer.apply {
            doOnRunning {
                baseUiView?.loadingBinding?.root?.visible()
            }
            doOnError {
                println()
            }
            doOnSuccess {
                baseUiView?.loadingBinding?.root?.gone()
                it.data?.setOnListScrollEndListener(picAdapter) {
                    viewModel.loadPic()
                }
                picAdapter.refreshPageHelper(it.data) { datas ->
                    if (it.data?.hasNextPage == true) {
                        datas.add(Pair(true, "正在加载"))
                    } else {
                        datas.add(Pair(false, "已加载完所有数据"))
                    }
                    datas
                }
            }
            doSuccess {
                println()
            }
        }
    }

    override fun initData() {
        super.initData()
        if (datas.isEmpty()) {
            viewModel.loadPic()
        } else {
            picAdapter.refreshList(datas.onEach {
                it.isBlur = true
            })
        }
    }

    override fun isNeedBaseUiView(): Boolean {
        return true
    }

    private fun testObserver() {
        //系统函数：带有生命周期的注册
        viewModel.picData.observe(viewLifecycleOwner) {

        }
        //系统函数：无生命周期的注册
        viewModel.picData.observeForever {

        }
        //扩展函数：带有生命周期的注册，带有根据状态联动的view
        viewModel.picData.observerAttachView {

        }
        //扩展函数：无生命周期的注册，带有根据状态联动的view
        viewModel.picData.observerStatusDataAttachView(null, this) {

        }
        //扩展函数：带有生命周期的注册,数据不是null，而且状态是成功回调
        viewModel.picData.doSuccess {

        }
        //扩展函数：无生命周期的注册,数据不是null，而且状态是成功回调
        viewModel.picData.doOnSuccess(null) {

        }
        //扩展函数：带有生命周期的注册,数据不是null，内部监听状态
        viewModel.picData.observerStatus {

        }
        //扩展函数：无生命周期的注册,数据不是null，内部监听状态
        viewModel.picData.observeStatusData(null) {

        }
    }
}